import React, { createContext, useContext, useReducer, useEffect, useCallback } from 'react';
import type { GameContextType, GameState, Order, OvenSlot, PizzaType, OrderStatus, OvenSlotStatus } from './types.ts';
import { pizzaRecipes } from './pizzaRecipes';

// 初始游戏状态
const initialState: GameState = {
  money: 100,
  reputation: 80,
  orders: [],
  ovenSlots: [
    { id: 1, status: 'empty' },
    { id: 2, status: 'empty' },
    { id: 3, status: 'empty' }
  ],
  selectedIngredients: [],
  currentOrderId: undefined,
  gameActive: false,
  gameOver: false
};

// Action类型定义
type GameAction =
  | { type: 'START_GAME' }
  | { type: 'PAUSE_GAME' }
  | { type: 'RESTART_GAME' }
  | { type: 'ADD_ORDER'; payload: Order }
  | { type: 'UPDATE_ORDER_STATUS'; payload: { orderId: string; status: OrderStatus } }
  | { type: 'UPDATE_MONEY'; payload: number }
  | { type: 'UPDATE_REPUTATION'; payload: number }
  | { type: 'SELECT_ORDER'; payload: string | undefined }
  | { type: 'SELECT_INGREDIENT'; payload: string }
  | { type: 'RESET_SELECTED_INGREDIENTS' }
  | { type: 'UPDATE_OVEN_SLOT'; payload: OvenSlot }
  | { type: 'SET_GAME_OVER' }
  | { type: 'CLEANUP_ORDERS'; payload: Order[] };

// Reducer函数
const gameReducer = (state: GameState, action: GameAction): GameState => {
  switch (action.type) {
    case 'START_GAME':
      return { ...state, gameActive: true, gameOver: false };
    case 'PAUSE_GAME':
      return { ...state, gameActive: false };
    case 'RESTART_GAME':
      return initialState;
    case 'ADD_ORDER':
      return { ...state, orders: [...state.orders, action.payload] };
    case 'UPDATE_ORDER_STATUS':
      return {
        ...state,
        orders: state.orders.map(order =>
          order.id === action.payload.orderId
            ? { ...order, status: action.payload.status }
            : order
        )
      };
    case 'UPDATE_MONEY':
      return { ...state, money: Math.max(0, state.money + action.payload) };
    case 'UPDATE_REPUTATION':
      const newReputation = Math.max(0, Math.min(100, state.reputation + action.payload));
      return {
        ...state,
        reputation: newReputation,
        gameOver: newReputation <= 0
      };
    case 'SELECT_ORDER':
      return { ...state, currentOrderId: action.payload };
    case 'SELECT_INGREDIENT':
      // 避免重复添加相同的材料
      if (state.selectedIngredients.includes(action.payload)) {
        return state;
      }
      return {
        ...state,
        selectedIngredients: [...state.selectedIngredients, action.payload]
      };
    case 'RESET_SELECTED_INGREDIENTS':
      return { ...state, selectedIngredients: [] };
    case 'UPDATE_OVEN_SLOT':
      return {
        ...state,
        ovenSlots: state.ovenSlots.map(slot =>
          slot.id === action.payload.id ? action.payload : slot
        )
      };
    case 'SET_GAME_OVER':
      return { ...state, gameOver: true, gameActive: false };
    case 'CLEANUP_ORDERS':
      return { ...state, orders: action.payload };
    default:
      return state;
    }
};

// 创建Context
const GameContext = createContext<GameContextType | undefined>(undefined);

// GameProvider组件
export const GameProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(gameReducer, initialState);

  // 生成新订单
  const generateNewOrder = useCallback(() => {
    if (!state.gameActive) return;

    const pizzaTypes: PizzaType[] = ['Margherita', 'Pepperoni', 'Vegetarian', 'MeatLovers'];
    const randomPizzaType = pizzaTypes[Math.floor(Math.random() * pizzaTypes.length)];
    
    const newOrder: Order = {
      id: `${Date.now()}-${Math.floor(Math.random() * 1000)}`,
      pizzaType: randomPizzaType,
      status: 'pending',
      createdAt: Date.now(),
      timeLimit: 60 // 60秒
    };

    dispatch({ type: 'ADD_ORDER', payload: newOrder });
  }, [state.gameActive]);

  // 检查订单是否超时
  const checkOrderTimeouts = useCallback(() => {
    if (!state.gameActive) return;

    const currentTime = Date.now();
    state.orders.forEach(order => {
      if (order.status === 'pending' || order.status === 'in-progress') {
        const timeElapsed = (currentTime - order.createdAt) / 1000;
        if (timeElapsed > order.timeLimit) {
          // 订单超时，扣减声誉
          dispatch({ type: 'UPDATE_ORDER_STATUS', payload: { orderId: order.id, status: 'failed' } });
          dispatch({ type: 'UPDATE_REPUTATION', payload: -10 });
        }
      }
    });

    // 清理已完成或失败的订单（3秒后移除）
    const updatedOrders = state.orders.filter(order => {
      if ((order.status === 'completed' || order.status === 'failed') &&
          (currentTime - order.createdAt) / 1000 > 3) {
        return false;
      }
      return true;
    });

    if (updatedOrders.length !== state.orders.length) {
      dispatch({ type: 'CLEANUP_ORDERS', payload: updatedOrders });
    }
  }, [state.gameActive, state.orders]);

  // 更新烤炉状态
  const updateOvenSlots = useCallback(() => {
    if (!state.gameActive) return;

    const currentTime = Date.now();
    state.ovenSlots.forEach(slot => {
      if (slot.status === 'baking' && slot.startTime) {
        const elapsedTime = (currentTime - slot.startTime) / 1000;
        const bakeTime = slot.pizza ? pizzaRecipes[slot.pizza].bakeTime : 0;
        const remainingTime = bakeTime - elapsedTime;

        if (remainingTime <= 0) {
          // 烘烤完成
          dispatch({
            type: 'UPDATE_OVEN_SLOT',
            payload: { ...slot, status: 'ready', remainingTime: 0 }
          });
        } else {
          // 更新剩余时间
          dispatch({
            type: 'UPDATE_OVEN_SLOT',
            payload: { ...slot, remainingTime }
          });
        }
      } else if (slot.status === 'ready' && slot.startTime) {
        // 检查是否烤焦（完成后30秒）
        const elapsedTimeSinceReady = (currentTime - slot.startTime - (slot.pizza ? pizzaRecipes[slot.pizza].bakeTime * 1000 : 0)) / 1000;
        if (elapsedTimeSinceReady > 30) {
          dispatch({
            type: 'UPDATE_OVEN_SLOT',
            payload: { ...slot, status: 'burnt' }
          });
          // 添加烤糊惩罚
          dispatch({ type: 'UPDATE_REPUTATION', payload: -10 });
          dispatch({ type: 'UPDATE_MONEY', payload: -5 });
        }
      }
    });
  }, [state.gameActive, state.ovenSlots]);

  // 游戏主循环
  useEffect(() => {
    if (!state.gameActive) return;

    const gameLoop = setInterval(() => {
      checkOrderTimeouts();
      updateOvenSlots();
    }, 1000);

    // 每20秒生成一个新订单
    const orderInterval = setInterval(generateNewOrder, 20000);

    // 检查游戏是否结束
    if (state.reputation <= 0) {
      dispatch({ type: 'SET_GAME_OVER' });
    }

    return () => {
      clearInterval(gameLoop);
      clearInterval(orderInterval);
    };
  }, [state.gameActive, state.reputation, checkOrderTimeouts, updateOvenSlots, generateNewOrder]);

  // 游戏控制函数
  const startGame = () => {
    dispatch({ type: 'START_GAME' });
    // 立即生成第一个订单
    generateNewOrder();
  };

  const pauseGame = () => {
    dispatch({ type: 'PAUSE_GAME' });
  };

  const restartGame = () => {
    dispatch({ type: 'RESTART_GAME' });
  };

  // 订单选择
  const selectOrder = (orderId: string) => {
    dispatch({ type: 'SELECT_ORDER', payload: orderId });
    resetSelectedIngredients();
  };

  // 材料选择
  const selectIngredient = (ingredient: string) => {
    dispatch({ type: 'SELECT_INGREDIENT', payload: ingredient });
  };

  const resetSelectedIngredients = () => {
    dispatch({ type: 'RESET_SELECTED_INGREDIENTS' });
  };

  // 烹饪披萨
  const cookPizza = (): boolean => {
    if (!state.currentOrderId) return false;

    const currentOrder = state.orders.find(order => order.id === state.currentOrderId);
    if (!currentOrder) return false;

    const recipe = pizzaRecipes[currentOrder.pizzaType];
    
    // 检查材料是否正确
    const hasAllIngredients = recipe.ingredients.every(ing => 
      state.selectedIngredients.includes(ing)
    ) && state.selectedIngredients.length === recipe.ingredients.length;

    if (!hasAllIngredients) return false;

    // 查找空闲的烤炉槽位
    const emptySlot = state.ovenSlots.find(slot => slot.status === 'empty');
    if (!emptySlot) return false;

    // 更新订单状态
    dispatch({ type: 'UPDATE_ORDER_STATUS', payload: { orderId: currentOrder.id, status: 'in-progress' } });

    // 开始烘烤
    dispatch({
      type: 'UPDATE_OVEN_SLOT',
      payload: {
        ...emptySlot,
        status: 'baking',
        pizza: currentOrder.pizzaType,
        startTime: Date.now()
      }
    });

    // 重置选中的材料
    resetSelectedIngredients();

    return true;
  };

  // 从烤炉取出披萨
  const takePizzaFromOven = (slotId: number): PizzaType | null => {
    const slot = state.ovenSlots.find(s => s.id === slotId);
    if (!slot || (slot.status !== 'ready' && slot.status !== 'burnt') || !slot.pizza) {
      return null;
    }

    const pizzaType = slot.pizza;

    // 清空烤炉槽位
    dispatch({
      type: 'UPDATE_OVEN_SLOT',
      payload: { id: slotId, status: 'empty' }
    });

    return pizzaType;
  };

  // 交付披萨
  const deliverPizza = (orderId: string, pizzaType: PizzaType): boolean => {
    const order = state.orders.find(o => o.id === orderId);
    if (!order || order.status !== 'in-progress') {
      return false;
    }

    if (order.pizzaType === pizzaType) {
      // 交付成功
      const recipe = pizzaRecipes[pizzaType];
      dispatch({ type: 'UPDATE_MONEY', payload: recipe.value });
      dispatch({ type: 'UPDATE_REPUTATION', payload: 5 });
      dispatch({ type: 'UPDATE_ORDER_STATUS', payload: { orderId, status: 'completed' } });
      return true;
    } else {
      // 交付失败
      dispatch({ type: 'UPDATE_REPUTATION', payload: -5 });
      return false;
    }
  };

  const contextValue: GameContextType = {
    state,
    startGame,
    pauseGame,
    restartGame,
    selectOrder,
    selectIngredient,
    resetSelectedIngredients,
    cookPizza,
    takePizzaFromOven,
    deliverPizza
  };

  return (
    <GameContext.Provider value={contextValue}>
      {children}
    </GameContext.Provider>
  );
};

// 自定义Hook
export const useGame = () => {
  const context = useContext(GameContext);
  if (context === undefined) {
    throw new Error('useGame must be used within a GameProvider');
  }
  return context;
};
